package com.qf.mrmd.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qf.mrmd.entity.SysUser;
import com.qf.mrmd.dao.SysUserDao;
import com.qf.mrmd.exception.BusinessException;
import com.qf.mrmd.result.ResponseCode;
import com.qf.mrmd.result.ResponseData;
import com.qf.mrmd.service.SysUserService;
import com.qf.mrmd.util.TokenUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * (SysUser)表服务实现类
 *
 * @author makejava
 * @since 2021-07-21 10:38:15
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;

    @Value("${com.qf.appid}")
    private String appId;

    @Value("${com.qf.appsecret}")
    private String appSecret;


    /**
     * 通过ID查询单条数据
     *
     * @param uId 主键
     * @return 实例对象
     */
    @Override
    public SysUser queryById(Integer uId) {
        return this.sysUserDao.queryById(uId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<SysUser> queryAllByLimit(int offset, int limit) {
        return this.sysUserDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public SysUser insert(SysUser sysUser) {
        this.sysUserDao.insert(sysUser);
        return sysUser;
    }

    /**
     * 修改数据
     *
     * @param userInfo 实例对象
     * @return 实例对象
     */
    @Override
    public ResponseData update(String userInfo) {
        JSONObject jsonObject = JSONObject.parseObject(userInfo);
        SysUser sysUser = new SysUser();
        String token = jsonObject.getString("token");
        sysUser.setToken(token);
        List<SysUser> sysUsers = sysUserDao.queryAll(sysUser);
        if (sysUsers.size() == 0){
            return new ResponseData(ResponseCode.FAILED);
        }
        SysUser sysUser1 = sysUsers.get(0);
        sysUser1.setImg(jsonObject.getString("img"));
        sysUser1.setNickname(jsonObject.getString("nickname"));
        sysUser1.setSex(jsonObject.getString("sex"));
        int update = sysUserDao.update(sysUser1);
        if (update > 0){
            return  new ResponseData(ResponseCode.SUCCESS);
        }else {
            return  new ResponseData(ResponseCode.FAILED);
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param uId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer uId) {
        return this.sysUserDao.deleteById(uId) > 0;
    }

    @Transactional
    @Override
    public ResponseData login(String code) {
        //向微信服务端发送请求
        try {
            //配置访问地址
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
            //设置请求 需要jar包httpclient
            HttpGet httpGet = new HttpGet(url);
            //创建客户端对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //发送请求
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            //获取微信后台的响应值
            HttpEntity entity = httpResponse.getEntity();
            //将httpentity对象转换成字符串
            String s = EntityUtils.toString(entity);
            //将s转换成json对象
            JSONObject jsonObject = JSONObject.parseObject(s);
            String session_key = jsonObject.getString("session_key");
            String openid = jsonObject.getString("openid");
            //通过openid去获取对应的用户信息 openid是唯一的
            SysUser user = sysUserDao.queryByOpenId(openid);

            // 如果user为null，将openid和session_key插入到数据库中
            //通过openid和session_key实现一个加密token（随机的字符串）
            Md5Hash md5Hash = new Md5Hash(openid,session_key,100);
            String token = md5Hash.toString();
            if(user == null){
                SysUser sysUser = new SysUser();
                sysUser.setSessionkey(session_key);
                sysUser.setOpenid(openid);

                sysUser.setToken(token);
                int insert = sysUserDao.insert(sysUser);
                if (insert>0){
                    return new ResponseData(ResponseCode.SUCCESS,token);
                }else {
                    return new ResponseData(ResponseCode.FAILED);
                }
            }else {  //如果user有值，说明之前登陆过，要去更新session_key
                user.setSessionkey(session_key);
                user.setToken(token);
                int update = sysUserDao.update(user);
                if (update>0){
                    return new ResponseData(ResponseCode.SUCCESS,token);
                }else {
                    return new ResponseData(ResponseCode.FAILED);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseData(ResponseCode.FAILED);
        }

    }

    @Transactional
    @Override
    public SysUser adminLogin(SysUser sysUser) throws Exception {
        //先判定参数是否正常
        if (null == sysUser.getUname() || null == sysUser.getPassword()){
            throw  new BusinessException(ResponseCode.PARAM_EXCEPTION.getEcode(), ResponseCode.PARAM_EXCEPTION.getInfo());
        }
        SysUser user = sysUserDao.queryUserByuName(sysUser.getUname());
        if (user == null){
            throw new BusinessException(ResponseCode.USERINFO_EXCEPTION.getEcode(), ResponseCode.USERINFO_EXCEPTION.getInfo());
        }
        if (!sysUser.getPassword().equals(user.getPassword())){
            throw new BusinessException(ResponseCode.USERINFO_EXCEPTION.getEcode(), ResponseCode.USERINFO_EXCEPTION.getInfo());
        }
        //生成一个token
        String token = TokenUtil.getToken();
        user.setSysToken(token);
        //将token存入数据库（zhengq操作是放在redis）
        sysUserDao.update(user);
        //将用户信息返回给前端
        user.setPassword("");
        return user;
    }

    @Override
    public SysUser queryUserBySysToken(String token) {
        return  sysUserDao.queryUserBySysToken();
    }

}
